import dataStorage from '@ohos.data.storage';
import featureAbility from '@ohos.ability.featureAbility';

class Storage {
    rootPath;
    json = false;
    #getBuildPath = (path) => {
        return this.rootPath[0] === '/' ? path + this.rootPath : path + '/' + this.rootPath;
    }

    constructor(rootPath) {
        this.rootPath = rootPath;
    }
    isJSON() {
        this.json = true;
    }

    async put(key, val) {
        let path = await featureAbility.getContext().getFilesDir();
        let lastPath = this.#getBuildPath(path);
        let storage = dataStorage.getStorageSync(lastPath);
        if (typeof val === 'object' && val) {
            storage.putSync(key, JSON.stringify(val));
        } else {
            storage.putSync(key, val);
        }
        storage.flushSync();
    }

    async get(key) {
        let path = await featureAbility.getContext().getFilesDir();
        let lastPath = this.#getBuildPath(path);
        let storage = dataStorage.getStorageSync(lastPath);
        let data = storage.getSync(key, 'no data');
        if (data == 'no data') {
            console.error(`gzkemays error => get ${key} is null`);
        }
        if (data != 'no data' && this.json) {
            return JSON.parse(data);
        }
        return data;
    }
}

class Cache {
    map;
    size;
    constructor () {
        this.map = new Map();
    }
    set(key, value) {
        this.map.set(key, value);
    }
    get(key) {
        return this.map.get(key);
    }
    getKeys() {
        let keys = [];
        for (let key of this.map.keys()) {
            keys.push(key);
        }
        return keys;
    }
    getValues() {
        let values = [];
        this.map.forEach((value) => values.push(value));
        return values;
    }
    getEntry() {
        let entry = []
        this.map.forEach((value, key) => {
            entry.push({key, value});
        });
        return entry;
    }
}


export { Storage, Cache };